package state;

import state.util.array.ObjectArray;

public class GameTimer extends GameControl {
  private final int POOL_SIZE = 50;

  private ObjectArray timerListeners = ObjectArray.create(POOL_SIZE);

  public GameTimer(int delay) {
    setTimeInterval(delay);
    setRepeat(true);
  }
  
  private void expandSize() {
    ObjectArray tmp = ObjectArray.create(timerListeners.len() * 2);
    ObjectArray.arraycopy(timerListeners, 0, tmp, 0, timerListeners.len());
    timerListeners = tmp;
  }

  public void addTarget(TimerListener timerListener) {
    // Check if this listener exist
    for (int i = 0; i < timerListeners.len(); i++) {
      if (timerListeners.get(i) == timerListener) {
        return;
      }
    }

    // Put this listener to list
    boolean isNotEnoughSpace = true;
    for (int i = 0; i < timerListeners.len(); i++) {
      if (timerListeners.get(i) == null) {
        timerListeners.set(i, timerListener);
        isNotEnoughSpace = false;
        break;
      }
    }
    
    if (isNotEnoughSpace) {
      expandSize();
      addTarget(timerListener);
    }
  }

  public void removeTarget(TimerListener timerListener) {
    for (int i = 0; i < timerListeners.len(); i++) {
      if (timerListeners.get(i) == timerListener) {
        timerListeners.set(i, null);
        break;
      }
    }
  }

  public void perform() {
    for (int i = 0; i < timerListeners.len(); i++) {
      if (timerListeners.get(i) != null) {
        ((TimerListener) timerListeners.get(i)).doTask();
      }
    }
  }

  public void cancel() {
    stop();
  }

  public void setDelay(int delay) {
    setTimeInterval(delay);
  }

  public int getDelay() {
    return getTimeInterval();
  }
}
